// -*-mode:c++; coding:utf-8-*-

#include "logger.hpp"

#include "table_mutator.hpp"

namespace xbase
{

	void table_mutator::on_delete_response(protocol::packet_ptr packet,
					       const error_code &session_ec) {
		if(session_ec)
		{
			on_delete_error(session_ec);
		}
		else if(packet->get_type() != delete_table_resp::type)
		{
			on_delete_error(error::bad_packet_type);
		}
		else
		{
			const delete_table_resp *resp = boost::polymorphic_downcast<delete_table_resp*>(packet.get());
			const protocol::delete_table_response &body = resp->body();
			error_code ec = body.error_code();
			if(! ec)
			{
				dispatch_delete(ec);
			}
			else
			{
				on_delete_error(ec);
			}
		}
	}

	void table_mutator::on_delete_error(const error_code &ec) {
		LOG(ERROR, "delete table error, ec = " << ec
		    << " - " << ec.message()
		    << ", delete request = "
		    << m_delete_req_ptr->to_string());
		dispatch_delete(ec);
	}

	void table_mutator::on_create_response(protocol::packet_ptr packet,
					       const error_code &session_ec) {
		if(session_ec)
		{
			on_create_error(session_ec);
		}
		else if(packet->get_type() != create_table_resp::type)
		{
			on_create_error(error::bad_packet_type);
		}
		else
		{
			const create_table_resp *resp = boost::polymorphic_downcast<create_table_resp*>(packet.get());
			const protocol::create_table_response &body = resp->body();
			error_code ec = body.error_code();
			if(! ec)
			{
				dispatch_create(ec);
			}
			else
			{
				on_create_error(ec);
			}
		}
	}

	void table_mutator::on_create_error(const error_code &ec) {
		LOG(ERROR, "create table error, ec = " << ec
		    << " - " << ec.message()
		    << ", create request = "
		    << m_create_req_ptr->to_string());
		dispatch_create(ec);
	}

	void table_mutator::on_list_response(protocol::packet_ptr packet,
					     const error_code &session_ec) {
		if(session_ec)
		{
			on_list_error(table_name_vector(), session_ec);
		}
		else if(packet->get_type() != list_table_resp::type)
		{
			on_list_error(table_name_vector(), error::bad_packet_type);
		}
		else
		{
			const list_table_resp *resp = boost::polymorphic_downcast<list_table_resp*>(packet.get());
			const protocol::list_table_response &body = resp->body();
			error_code ec = body.error_code();
			if(! ec)
			{
				dispatch_list(body.m_table_names, ec);
			}
			else
			{
				on_list_error(table_name_vector(), ec);
			}
		}
	}

	void table_mutator::on_list_error(const table_name_vector &vec,
					  const error_code &ec) {
		LOG(ERROR, "list table error, ec = " << ec
		    << " - " << ec.message()
		    << ", list request = "
		    << m_list_req_ptr->to_string());
		dispatch_list(vec, ec);
	}

} // namespace xbase
